import { defaultOptions, renderAsync } from 'docx-preview'
import axios from 'axios'

// 读取url的blob文件
async function loadFileByUrl(url) {
  const res = await axios.get(url, { responseType: 'blob' })
  return res.data
}

/**
 * word转html
 */
export async function word2html(url) {
  const blob = await loadFileByUrl(url)
  const node = document.createElement('div')
  await renderAsync(blob, node, node, {
    ...defaultOptions
    // useBase64URL: true
    // debug: true
  })
  return node
}

// file转blob
export async function fileToBlob(file) {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.addEventListener('load', (e) => {
      const base64 = e.target.result
      const blob = new Blob([base64], { type: file.type })
      resolve(blob)
    })
    reader.readAsDataURL(file)
  })
}

// file转base64
export async function fileToBase64(file) {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.addEventListener('load', (e) => {
      resolve(e.target.result)
    })
    reader.readAsDataURL(file)
  })
}

/**
 * word转html
 */
export async function wordblob2html(blob) {
  const node = document.createElement('div')
  await renderAsync(blob, node, node, {
    ...defaultOptions
    // useBase64URL: true
    // debug: true
  })
  return node
}

// 加载图片
export async function loadImage(url) {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => resolve(img)
    img.onerror = () => resolve(null)
    img.src = url
  })
}

// 加载图片到canvas（解决原图灰色问题）
export async function loadImageCanvas(url) {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.naturalWidth
      canvas.height = img.naturalHeight
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0)
      resolve(canvas)
    }
    img.onerror = () => resolve(null)
    img.src = url
  })
}

// 图片对象转base64
export function getImageBase64(img, ext = 'jpeg') {
  var canvas = document.createElement('canvas') //创建canvas DOM元素，并设置其宽高和图片一样
  canvas.width = img.naturalWidth
  canvas.height = img.naturalHeight
  var ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height) //使用画布画图
  var dataURL = canvas.toDataURL('image/' + ext) //返回的是一串Base64编码的URL并指定格式
  canvas = null //释放
  return dataURL
}
